import { createContext, useEffect, useState } from 'react';
import create from 'zustand';

import { DialogTypes, MapDialogTypes } from './types-mapping';

type DynamicDialogStore = {
    type?: DialogTypes;
    // @ts-ignore
    dialogFnc?: () => ({ params: any }) => any;
};

const useDynamicDialogStore = create<DynamicDialogStore>(() => ({
    type: undefined,
    dialogFnc: undefined
}));

export const createDialog = (type: DialogTypes, dialogFnc: any) => {
    useDynamicDialogStore.setState({
        type,
        dialogFnc
    });
};

export const DialogContext = createContext({ value: { time: 900 }, setValue: undefined });

export const DialogProvider = ({ children }) => {
    const [value, setValue] = useState({ time: 900 });
    // eslint-disable-next-line react/no-children-prop
    return <DialogContext.Provider value={{ value, setValue }} children={children} />;
};

const DynamicDialog = () => {
    const { type, dialogFnc } = useDynamicDialogStore();
    const DialogComponent = MapDialogTypes.get(type);

    useEffect(() => {
        dialogFnc && dialogFnc();
    }, [dialogFnc]);

    return DialogComponent ? (
        <DialogProvider>
            <DialogComponent />
        </DialogProvider>
    ) : (
        <></>
    );
};

export default DynamicDialog;
